package org.zeroturnaround.javarebel.integration.jmonkey;

import org.zeroturnaround.bundled.javassist.*;
import org.zeroturnaround.javarebel.LoggerFactory;
import org.zeroturnaround.javarebel.integration.support.JavassistClassBytecodeProcessor;


public class JMonkeyBaseClassBytecodeProcessor extends JavassistClassBytecodeProcessor {


    public void process(ClassPool cp, ClassLoader cl, CtClass ctClass)
            throws Exception {
        patchBaseSimpleGame(ctClass);
        try {
            CtMethod initMethod = ctClass.getDeclaredMethod("initSystem");
            initMethod.insertAfter("org.zeroturnaround.javarebel.integration.jmonkey."+
                    "JMonkeyAppConfigReloader.initInstance($0);");
        } catch (NotFoundException e) {
            LoggerFactory.getInstance().error(e);
        }
    }

    private void patchBaseSimpleGame(CtClass ctClass) throws CannotCompileException {
        LoggerFactory.getInstance().echo("Patching the BaseSimpleGame class ..");
        ctClass.addField(CtField.make("public static com.jme.app.BaseSimpleGame instance;", ctClass));
        ctClass.addMethod(CtMethod.make("public void restartInstance() { initGame(); }", ctClass));
        ctClass.addMethod(CtMethod.make("public Object getInstance() { return instance; }", ctClass));
        ctClass.addMethod(CtMethod.make("public void setInstance(Object objectInstance)" +
                " {instance = objectInstance;}", ctClass));
    }
}